import axios from 'axios';
import {
	notification,
	Modal
} from 'ant-design-vue'
import sysConfig from "@/config";
import tool from '@/utils/tool';
import router from '@/router';
import {
	createVNode
} from 'vue'
import {
	userStore
} from '@/stores/userStore'

axios.defaults.baseURL = ''
axios.defaults.timeout = sysConfig.TIMEOUT

// HTTP request 拦截器
axios.interceptors.request.use(
	(config) => {
		// console.log('request.use')
		let token = tool.cookie.get(sysConfig.TOKEN_KEY);
		// console.log('token', token)
		if (token) {
			config.headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token
		}
		if (!sysConfig.REQUEST_CACHE && config.method === 'get') {
			config.params = config.params || {};
			config.params['_'] = new Date().getTime();
		}
		Object.assign(config.headers, sysConfig.HEADERS)
		// console.log('request.use', config)
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// HTTP response 拦截器
axios.interceptors.response.use(
	(response) => {
		// 只要code不等于200，都表示出错
		if (response.data.code === 200) {
			return Promise.resolve(response);
		} else if (response.data.code === 304) {
			Modal.confirm({
				title: 'Tips',
				content: response.data.msg || '当前用户已被登出或无权限访问当前资源，请尝试重新登录后再操作。',
				maskClosable: true,
				centered: true,
				footer: () => {
					return createVNode('div', {
						class: 'base-flex base-rows base-align-items-center base-justify-content-end base-mt20'
					}, [
						createVNode('button', {
							class: 'base-btn primary',
							onClick: (e) => {
								const useUserStore = userStore()
								useUserStore.loginOut()
								router.replace({
									path: '/login'
								});
								// 销毁弹窗
								Modal.destroyAll()
							}
						}, 'Login'),
					])
				},
			})
			// 在error回调里面，这里给啥，显示啥
			return Promise.reject(response.data);
		} else {
			// 在error回调里面，这里给啥，显示啥
			return Promise.reject(response.data);
			// notification.error({
			// 	message: '请求失败',
			// 	description: response.data.msg,
			// })
		}
	},
	(error) => {
		if (error.response) {
			if (error.response.status === 404) {
				notification.error({
					message: '请求错误',
					description: "Status:404，正在请求不存在的服务器记录！",
				})
			} else if (error.response.status === 500) {
				notification.error({
					message: '请求错误',
					description: error.response.data.msg || "Status:500，服务器发生错误！"
				});
			} else if (error.response.status === 401) {
				Modal.confirm({
					title: '无权限访问',
					content: '当前用户已被登出或无权限访问当前资源，请尝试重新登录后再操作。',
					maskClosable: false,
					centered: true,
					cancelText: '重新登录',
					onOk() {
						router.replace({
							path: '/login'
						});
					},
				})
			} else {
				notification.error({
					message: '请求错误',
					description: error.message || `Status:${error.response.status}，未知错误！`
				});
			}
		} else {
			notification.error({
				message: '请求错误',
				description: "请求服务器无响应！"
			});
		}
		return Promise.reject(error.response);
	}
);

var http = {

	/** get 请求
	 * @param  {{接口地址}} url
	 * @param  {{请求参数}} params
	 * @param  {{参数}} config
	 */
	get: function(url, params = {}, config = {}) {
		// console.log('请求参数', params)
		// console.log('请求地址', url)
		return new Promise((resolve, reject) => {
			axios({
				method: 'get',
				url: url,
				params: params,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				// console.log('请求失败', error)
				reject(error);
			})
		})
	},

	/** post 请求
	 * @param  {{接口地址}} url
	 * @param  {{请求参数}} data
	 * @param  {{参数}} config
	 */
	post: function(url, data = {}, config = {}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'post',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** put 请求
	 * @param  {{接口地址}} url
	 * @param  {{请求参数}} data
	 * @param  {{参数}} config
	 */
	put: function(url, data = {}, config = {}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'put',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** patch 请求
	 * @param  {{接口地址}} url
	 * @param  {{请求参数}} data
	 * @param  {{参数}} config
	 */
	patch: function(url, data = {}, config = {}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'patch',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** delete 请求
	 * @param  {{接口地址}} url
	 * @param  {{请求参数}} data
	 * @param  {{参数}} config
	 */
	delete: function(url, data = {}, config = {}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'delete',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** jsonp 请求
	 * @param  {接口地址} url
	 * @param  {JSONP回调函数名称} name
	 */
	jsonp: function(url, name = 'jsonp') {
		return new Promise((resolve) => {
			var script = document.createElement('script')
			var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
			script.id = _id
			script.type = 'text/javascript'
			script.src = url
			window[name] = (response) => {
				resolve(response)
				document.getElementsByTagName('head')[0].removeChild(script)
				try {
					delete window[name];
				} catch (e) {
					window[name] = undefined;
				}
			}
			document.getElementsByTagName('head')[0].appendChild(script)
		})
	}
}

export default http;